<?php

namespace App\Console\Commands\Transfer;

use App\Models\Ca\Customer;
use App\Models\Ca\CustomerDisease;
use App\Models\Ca\Disease;
use App\Models\Ca\Visit;
use App\Models\System\Area;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CustomerAreaCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'transfer:customerArea';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '迁移';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $provinceIds = Customer::query()->where('province_id', '>', 0)->where('province_id', '<', 1000)->groupBy('province_id')->pluck('province_id');
        foreach ($provinceIds as $provinceId) {
            $provinceName = DB::connection('S')->table('bs_area')->where('id', '=', $provinceId)->value('name');
            if (Str::endsWith($provinceName, '省'))
                $provinceName = substr($provinceName, 0, strlen($provinceName) - strlen('省'));
            if (Str::endsWith($provinceName, '市'))
                $provinceName = substr($provinceName, 0, strlen($provinceName) - strlen('市'));
            $newId = Area::query()->where('name', 'like', $provinceName . '%')->where('level', '=', 1)->value('id');
            if (empty($newId)) {
                $this->output->warning('省不存在：' . $provinceName);
            } else {
                Customer::query()->where('province_id', '=', $provinceId)->update([
                    'province_id' => $newId
                ]);
            }
        }
        return;
        $cityIds = Customer::query()->where('city_id', '>', 0)->where('city_id', '<', 1000)->groupBy('city_id')->pluck('city_id');
        foreach ($cityIds as $cityId) {
            $cityName = DB::connection('S')->table('bs_area')->where('id', '=', $cityId)->value('name');
            $cityName = trim($cityName, '市');
            $newId = Area::query()->where('name', 'like', $cityName . '%')->where('level', '=', 2)->value('id');
            if (empty($newId)) {
                $this->output->warning('市不存在：' . $cityName);
            } else {
                Customer::query()->where('city_id', '=', $cityId)->update([
                    'city_id' => $newId
                ]);
            }
        }
    }
}